import { post } from '@/api/http'
import { ref } from 'vue'
import { debounce } from "lodash";
export function saveOrUpdateGridState(fileName: string,gridOption:any,colApi: any, columnDefs: any) {
    //fileName:文件名
    //gridOption:表格配置项
    //colApi:列（params.colApi)
    //columnDefs:默认表头排序
    //保存方法
    const saveGridStateFun = ()=>{
        const columnState = colApi.value.getColumnState();
        if (columnState) {
            post({
                url: 'admin/acl/MenuSet/insert',
                data: {
                    onlyKey: fileName,
                    head: JSON.stringify(columnState)
                }
            }).then(response => {
            }).catch(err => {
                console.log(err)
            })
        }
    }
    let fun = debounce(saveGridStateFun, 1000,{})
    const saveGridState = () => {
        fun()
    }
    
        //更新方法
    const updateGridState = () => {
        // console.log('调用更新方法前获取到的列数据',columnDefs)
        return new Promise((resolve, reject) => {
            post({
                url: 'admin/acl/MenuSet/getMenuSet',
                data: {
                    onlyKey: fileName
                }
            }).then(res => {
                // console.log(res)
                if (res.code == 200) {
                     if(res.data.list!=null){
                        colApi.value.applyColumnState({ 
                            state:JSON.parse(res.data.list.head) ,
                            applyOrder: true
                        });
                        let allColumnIds = []
                       const columns = colApi.value.getColumns()
                       if (columns.length > 0) {
                        columns.forEach((column) => {
                            if (!column.colDef.checkboxSelection) {
                                allColumnIds.push(column.getId());
                            }
                          });
                          colApi.value.autoSizeColumns(allColumnIds, false);
                       }
                     }
                }
            }).catch(err => {
                console.log(err)
            }).finally(() => {
                resolve()
            })
        })

    }
    return { saveGridState, updateGridState }
}